var NVC_Opt = null;
var ic = null;
var vm = new Vue({
    el:'#rrapp',
    data:{
        /* 提交表单 */
        seller: {},
        /* 省市区数据 */
        regionOptions: [],
        /* 所属类型 */
        operateTypeOptions:[{
            value: '商务印刷',
            label: '商务印刷'
        }, {
            value: '包装印刷',
            label: '包装印刷'
        }, {
            value: '广告标识',
            label: '广告标识'
        }, {
            value: '办公物料',
            label: '办公物料'
        }],
        /* 智能验证 */
        vericode: {
            aliVerifyStatus: false,
            aliSessionId: '',
            aliToken: '',
            aliSig: '',
            aliScene: '',
        },
        /* 倒计时 */
        timeDown: {
            buttonName: "立即获取",
            disable: false,
            time: 60
        },

        /* 表单校验 */
        rules: {
            sellerMobile: [
                { required: true, message: '请输入手机号码', trigger: 'blur' },
                { validator: function (rules, value, callback) {
                        var reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
                        if (!reg.test(value)){
                            callback(new Error('手机号码格式不对'));
                        }else {
                            callback();
                        }
                    },trigger: 'blur'
                },
            ],
            veriCode: [
                { required: true, message: '请输入短信验证码', trigger: 'blur' },
            ],
            sellerQq: [
                { required: true, message: '请输入qq号码', trigger: 'blur' },
            ],
            name: [
                { required: true, message: '请输入联系人名称', trigger: 'blur' },
            ],
            sellerEmail: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { type: 'email', message: '邮箱格式不对', trigger: 'blur' }
            ],
            doorheadName: [
                { required: true, message: '请输入门头照名称', trigger: 'blur' },
            ],
            sellerName: [
                { required: true, message: '请输入子公司名称', trigger: 'blur' },
            ],
            areaId: [
                { required: true, message: '请选择子公司地址', trigger: 'change' },
            ],
            addr: [
                { required: true, message: '请输入详细地址', trigger: 'blur' },
            ],
            logoUrl: [
                { required: true, message: '请上传门头照', trigger: 'blur' },
            ],
            businessUrl: [
                { required: true, message: '请上传营业执照', trigger: 'blur' },
            ],
        }
    },
    mounted: function () {
        this.filesUploadInit();
        this.queryArea();
        this.smartCaptchaInit();
    },
    methods: {
        /* 初始化阿里智能验证 */
        /**
         * 1.window.NVC_Opt全局变量的声明一定要在”//g.alicdn.com/sd/nvc/1.1.112/guide.js” 资源引入之前配置完毕
         * 2.new smartCaptcha的声明需要在window.NVC_Opt和”//g.alicdn.com/sd/nvc/1.1.112/guide.js” 资源引入之后配置
         */
        smartCaptchaInit: function () {
            var self = this;
            NVC_Opt = {
                appkey:'FFFF00000000017E28ED',
                scene:'ic_register',
                renderTo:'#captcha',
                trans: {"key1": "code0", "nvcCode": 200},
                elements: [
                    '//img.alicdn.com/tfs/TB17cwllsLJ8KJjy0FnXXcFDpXa-50-74.png',
                    '//img.alicdn.com/tfs/TB17cwllsLJ8KJjy0FnXXcFDpXa-50-74.png'
                ],
                bg_back_prepared: '//img.alicdn.com/tps/TB1skE5SFXXXXb3XXXXXXXXXXXX-100-80.png',
                bg_front: '',
                obj_ok: '//img.alicdn.com/tfs/TB1rmyTltfJ8KJjy0FeXXXKEXXa-50-74.png',
                bg_back_pass: '//img.alicdn.com/tfs/TB1KDxCSVXXXXasXFXXXXXXXXXX-100-80.png',
                obj_error: '//img.alicdn.com/tfs/TB1q9yTltfJ8KJjy0FeXXXKEXXa-50-74.png',
                bg_back_fail: '//img.alicdn.com/tfs/TB1w2oOSFXXXXb4XpXXXXXXXXXX-100-80.png',
                upLang:{"cn":{
                        _ggk_guide: "请摁住鼠标左键，刮出两面盾牌",
                        _ggk_success: "恭喜您成功刮出盾牌<br/>继续下一步操作吧",
                        _ggk_loading: "加载中",
                        _ggk_fail: ['呀，盾牌不见了<br/>请', "javascript:noCaptcha.reset()", '再来一次', '或', "http://survey.taobao.com/survey/QgzQDdDd?token=%TOKEN", '反馈问题'],
                        _ggk_action_timeout: ['我等得太久啦<br/>请', "javascript:noCaptcha.reset()", '再来一次', '或', "http://survey.taobao.com/survey/QgzQDdDd?token=%TOKEN", '反馈问题'],
                        _ggk_net_err: ['网络实在不给力<br/>请', "javascript:noCaptcha.reset()", '再来一次', '或', "http://survey.taobao.com/survey/QgzQDdDd?token=%TOKEN", '反馈问题'],
                        _ggk_too_fast: ['您刮得太快啦<br/>请', "javascript:noCaptcha.reset()", '再来一次', '或', "http://survey.taobao.com/survey/QgzQDdDd?token=%TOKEN", '反馈问题']
                    }
                }
            }
            $.getScript("//g.alicdn.com/sd/nvc/1.1.112/guide.js",function(){
                self.smartCaptchaVerify();
            });
        },
        /* 智能验证 */
        smartCaptchaVerify: function () {
            var self = this;
            ic = new smartCaptcha({
                renderTo: '#sc1',
                width: 300,
                height: 32,
                default_txt: '点击按钮开始智能验证',
                success_txt: '验证成功',
                fail_txt: '验证失败，请在此点击按钮刷新',
                scaning_txt: '智能检测中',
                success: function(data) {
                    self.vericode.aliVerifyStatus = true;
                    self.vericode.aliSessionId = data.sessionId;
                    self.vericode.aliSig = data.sig;
                    self.vericode.aliToken = NVC_Opt.token;
                    self.vericode.aliScene = NVC_Opt.scene;
                },
            });
            ic.init();
        },
        /* 初始化文件上传  */
        filesUploadInit: function () {
            var self = this;
            $.files_up_oss({
                id: ["upload1", 'upload2'],//按钮id
                url: "/sys/oss/getSignature",
                dir: "test/",
                file_type: "jpg,png,gif,psd,ai,cdr,eps,ppt,word,excel,pdf,tiff,rar,zip,7z",
                size: "100mb",//mb
                view_url: "https://ziyunoss.oss-cn-hangzhou.aliyuncs.com/"
            }, function (index_number, json) {
                console.info('files_up_oss[index_number:' + index_number + '],[json:'+ json +']');
                if (json.Status == 'OK'){
                    var name = json.oldFilename.replace(/'/g, '');
                    if (index_number == 0){
                        Vue.set(self.seller, 'logoUrl', json.filename);
                    }else {
                        Vue.set(self.seller, 'businessUrl', json.filename);
                    }
                }else {
                    alert("OSS上传失败，请联系后台管理员！");
                }
            });
        },
        /* 初始化省市区数据 */
        queryArea: function () {
            var self = this;
            $.get(baseURL + "freightages/sdbectoolsregions/queryRegionsSascade", function(r){
                self.regionOptions = JSON.parse(r.list);
            });
        },
        /* 获取验证码 */
        queryVerifyCode: function () {
            var self = this;
            if (isBlank(self.seller.sellerMobile)){
                alert("请填写手机号码！");
                return false;
            }
            if (!self.vericode.aliVerifyStatus){
                alert("请点击智能验证！");
                return false;
            }
            var postData = {
                mobile: self.seller.sellerMobile,
                aliSessionId: self.vericode.aliSessionId,
                aliToken: self.vericode.aliToken,
                aliSig: self.vericode.aliSig,
                aliScene: self.vericode.aliScene
            }

            $.ajax({
                type: "POST",
                url: baseURL + "supp/sellerinfo/queryVerifyCode",
                contentType: "application/json",
                data: JSON.stringify(postData),
                success: function(r){
                    if(r.code === 0){
                        self.verifyTimeOut();
                        self.vericode.aliVerifyStatus = false;
                        ic.reset();
                        alert('验证码发送成功！');
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 获取验证码倒计时 */
        verifyTimeOut: function () {
            var self = this;
            self.timeDown.disable = true;
            var interval = window.setInterval(function() {
                self.timeDown.buttonName = '（' + self.timeDown.time + '秒）后重新发送';
                --self.timeDown.time;
                if(self.timeDown.time < 0) {
                    self.timeDown.buttonName = "重新发送";
                    self.timeDown.time = 60;
                    self.timeDown.disable = false;
                    window.clearInterval(interval);
                }
            }, 1000);
        },
        /* 提交表单数据 */
        saveInfo: function () {
            var self = this;
            var access = false;
            self.$refs['seller'].validate(function (valid) {
                if (valid){
                    access = true;
                }
            });
            if (!access){
                return false;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "supp/sellerinfo/saveSubSellerInfo",
                contentType: "application/json",
                data: JSON.stringify(vm.seller),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){

                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 省市区选择事件 */
        handleRegionChange: function(val) {
            var values = val.join(',').split(',');
            var areaId = values[val.length-1];
            this.seller.areaId = areaId;
            var lableObj = this.getCascaderObj(val, this.regionOptions);
            var lable = lableObj.join(',').replace(new RegExp(',', 'g'), ' ');
            this.seller.area = lable;
        },
        /* 获取省市区名称 */
        getCascaderObj: function (val, opt) {
            return val.map(function (value, index, array) {
                for (var itm in opt) {
                    if (opt[itm].value == value) {
                        var label = opt[itm].label;
                        opt = opt[itm].children; return label;
                    }
                }
                return null;
            });
        },
    }
});